/**
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.solarchallenge.server.domain;

import com.google.solarchallenge.server.enums.OAuthProviderEnum;
import com.google.solarchallenge.shared.dtos.OAuthProviderDto;
import com.google.solarchallenge.shared.exceptions.InvalidClientInputException;

/**
 * Domain object for OAuthProvider.
 *
 * @author Arjun Satyapal
 */
public class OAuthProviderDao implements AbstractDao {
  protected OAuthProviderEnum oAuthProvider;
  protected String consumerKey;
  protected String consumerSecret;

  @Override
  public StringBuilder getStringBuilder() {
    StringBuilder builder = new StringBuilder();
    builder.append("OAuthProvider[").append(oAuthProvider);
    builder.append("], consumerKey[").append(consumerKey);
    builder.append("], consumerSecret[").append(consumerSecret);
    builder.append("].");

    return builder;
  }

  @Override
  public String toString() {
   return getStringBuilder().toString();
  }

  @Override
  public String validate() {
    StringBuilder builder = new StringBuilder("");

    if (oAuthProvider == null) {
      builder.append("oAuthProvider cannot be null.\n");
    }
    if (consumerKey.isEmpty()) {
      builder.append("consumerKey is empty.\n");
    }
    if (consumerSecret.isEmpty()) {
      builder.append("consumerSecret is empty.\n");
    }
    return builder.toString();
  }

  private OAuthProviderDao() {
  }

  public OAuthProviderEnum getOAuthProvider() {
    return oAuthProvider;
  }

  public String getConsumerKey() {
    return consumerKey;
  }

  public String getConsumerSecret() {
    return consumerSecret;
  }

  public static OAuthProviderDao fromOAuthProviderDto(OAuthProviderDto dto) {
    OAuthProviderDao oAuthProviderDao = new OAuthProviderDao();

    if (!dto.validate().isEmpty()) {
      throw new InvalidClientInputException(
          "Invalid UserAccountDto with Error : [" + dto.validate() + "].");
    }

    OAuthProviderEnum oauthProviderEnum = null;
    try {
      oauthProviderEnum = OAuthProviderEnum.valueOf(dto.getOAuthProvider());
    } catch (IllegalArgumentException e) {
      throw new InvalidClientInputException("Invalid OAuthProvider["
          + dto.getOAuthProvider() + "].");
    }

    oAuthProviderDao.oAuthProvider = oauthProviderEnum;
    oAuthProviderDao.consumerKey = dto.getConsumerKey();
    oAuthProviderDao.consumerSecret = dto.getConsumerSecret();
    return oAuthProviderDao;
  }
}
